package de.bht.cge.flightsim.game;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import de.bht.cge.flightsim.treeplanter.TreePlanter;
import de.bht.cge.flightsim.util.Settings;
import de.bht.jvr.collada14.loader.ColladaLoader;
import de.bht.jvr.core.Finder;
import de.bht.jvr.core.GroupNode;
import de.bht.jvr.core.SceneNode;
import de.bht.jvr.core.ShaderMaterial;
import de.bht.jvr.core.ShapeNode;
import de.bht.jvr.core.Transform;
import de.bht.jvr.math.Vector3;

public class Ground extends Base
{
    private int pos;
    private String terrainname;
    private boolean treeEnabled=true;

    public Ground(float scale, int pos, Vector3 v, ShaderMaterial sm, String terrain, GroupNode root)
    {
        super(scale, "Ground");
        this.setPos(pos);
        this.setPosition(v);
        this.setTerrainname(terrain);
        try
        {
            this.Build(sm, root);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private static Map<String, SceneNode> loadedScenes=new HashMap<String, SceneNode>();

    private static SceneNode loadScene(String path) throws Exception
    {
        SceneNode scene=loadedScenes.get(path);
        if (scene==null)
        {
            scene=ColladaLoader.load(new File(path));
            loadedScenes.put(path, scene);
        }

        GroupNode erg = new GroupNode();
        erg.addChildNode(scene);
        return erg;
    }

    private SceneNode vegetation = null;
    public void Build(ShaderMaterial sm, GroupNode root) throws Exception
    {

        sm.setMaterialClass(this.getName());
        SceneNode scene=loadScene("meshes/"+this.terrainname);
        scene.setTransform(Transform.scale(this.getScale()));
        ShapeNode shape=Finder.find(scene, ShapeNode.class, null);
        shape.setMaterial(sm);

        vegetation=TreePlanter.makeVegetation(shape, shape.getWorldTransform(this), GroundBuilder.trees, -Settings.GroundScale, 10*Settings.GroundScale);

        this.addChildNode(vegetation);

        this.addChildNode(scene);
        this.setTransform(Transform.translate(this.getPosition()));
        root.addChildNode(this);

    }

    public int getPos()
    {
        return pos;
    }

    public void setPos(int pos)
    {
        this.pos=pos;
    }

    private String getTerrainname()
    {
        return terrainname;
    }

    private void setTerrainname(String terrainname)
    {
        this.terrainname=terrainname;
    }

    public boolean isTreeEnabled()
    {
        return treeEnabled;
    }

    public void setTreeEnabled(boolean treeEnabled)
    {
        if(vegetation != null)
        {
            vegetation.setEnabled(treeEnabled);
        }
        this.treeEnabled=treeEnabled;
    }

}
